package com.acheng.achengutils.utils;

import android.content.Context;
import android.util.Base64;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import java.security.Key;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 跟App相关的辅助类
 *
 * @author
 */
public class AppUtils {


    private AppUtils() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");

    }

    private static Toast mToast;

    /**
     * 显示Toast
     */
    public static void showToast(Context context, CharSequence text) {
        if (mToast == null) {
            mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(text);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    /**
     * 统一加密方法
     *
     * @param text //要加密的字符串
     * @return
     * @throws Exception
     */
    public static String encrypt(String text) throws Exception {

        String key = "@supper##ship@0123456789".substring(0, 8);                               //私钥   AES固定格式为128/192/256 bits.即：16/24/32bytes。DES固定格式为128bits，即8bytes。

        byte[] IV = {0x12, 0x34, 0x56, 0x78, 0x04, 0x12, 0x55, 0x11};               //初始化向量参数，AES 为16bytes. DES 为8bytes.


        Key keySpec = new SecretKeySpec(key.getBytes(), "DES");                       //两DES个参数，第一个为私钥字节数组， 第二个为加密方式 AES或者DES

        IvParameterSpec ivSpec = new IvParameterSpec(IV);

        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");                     //实例化加密类，参数为加密方式，要写全

        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);                              //初始化，此方法可以采用三种方式，按服务器要求来添加。（1）无第三个参数（2）第三个参数为SecureRandom random = new SecureRandom();中random对象，随机数。(AES不可采用这种方法)（3）采用此代码中的IVParameterSpec

        byte[] b = cipher.doFinal(text.getBytes());                                 //加密操作,返回加密后的字节数组，然后需要编码。主要编解码方式有Base64, HEX, UUE, 7bit等等。此处看服务器需要什么编码方式


        return base64Encode(b);

    }

    public static String base64Encode(byte[] s) {
        if (s == null)
            return null;
        String enToStr = Base64.encodeToString(s, Base64.DEFAULT);

        return enToStr;
    }

    /**
     * 截图数字作为手机号码
     *
     * @param str
     * @return
     */
    public static String getNum(String str) {
        String str2 = "";
        str = str.trim();
        if (str != null && !"".equals(str)) {
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                    str2 += str.charAt(i);
                }
            }
        }
        return str2;
    }


    private static String TruncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;
        strURL = strURL.trim().toLowerCase(Locale.getDefault());
        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1) {
            if (arrSplit.length > 1) {
                if (arrSplit[1] != null) {
                    strAllParam = arrSplit[1];
                }
            }
        }
        return strAllParam;
    }

    /**
     * 解析出url参数中的键值对
     *
     * @param URL
     * @return
     */
    public static Map<String, String> UrlSplitMap(String URL) {
        Map<String, String> mapRequest = new HashMap<>();
        String[] arrSplit = null;
        String strUrlParam = TruncateUrlPage(URL);
        if (strUrlParam == null) {
            return mapRequest;
        }
        //每个键值为一组
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");
            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (arrSplitEqual[0] != "") {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }


    /**
     * 键盘是否打开
     *
     * @param c
     * @return
     */
    public static boolean isKeyOpen(Context c) {
        InputMethodManager imm = (InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();//isOpen若返回true，则表示输入法打开

        return isOpen;
    }

    /**
     * 是否是手机号
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNumber(String mobiles) {
        return Pattern
                .compile("^1[3-8][0-9]{9}$")
                .matcher(mobiles).matches();
    }


    public static String cutNum(String str) {

        String temp = "";

        String input = str;
        String regex = "\\d+(\\.\\d+)?";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            temp = matcher.group();

        }

        return temp;

    }


}


